package com.hnichr.crm.biz.customer.api;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hnichr.crm.biz.util.RSAUtils;
import com.hnichr.crm.common.customer.entity.CrmCustomer;
import com.hnichr.crm.common.customer.service.CrmCustomerApiService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author Zhangww
 * @date 2023/5/12 10:35
 */
@Slf4j
@Tag(name = "客户管理服务接口", description = "客户管理服务")
@RestController()
@RequestMapping("/api/customer/")
public class CrmCustomerApi {

    private static final Logger logger = LoggerFactory.getLogger(CrmCustomerApi.class);

    @Autowired
    private CrmCustomerApiService crmCustomerApiService;

    private String secret="mgr%j%l)";
    //采用公钥加密，私钥解密
    private static final String PUBLIC_KEY="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQOIxI6PMTPlFi12LLTVSVUGFK4AS98QlT+YjZaUVI+87VXOCZ+hSZE1V1TjWi6JzfXJZJF3ZGFjDULrQF3RMC073Rs7wM6uibpsqgJzjpjR44fgG0Z93q223DcyxIScG/ABA0f1Z+NDP2xgGZWiIIBcrZ8p31e1hgmLo+gtdSbwIDAQAB";
    //    private static final String PRIVATE_KEY="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJA4jEjo8xM+UWLXYstNVJVQYUrgBL3xCVP5iNlpRUj7ztVc4Jn6FJkTVXVONaLonN9clkkXdkYWMNQutAXdEwLTvdGzvAzq6JumyqAnOOmNHjh+AbRn3erbbcNzLEhJwb8AEDR/Vn40M/bGAZlaIggFytnynfV7WGCYuj6C11JvAgMBAAECgYAExepWq2cIFwLoi4pYgimve2aM7NcbVjPh1Jtj3qkNXlAdHaLNVcqCunIUnM8Hoj0240CSELW4YhmhnB4XJ5bub0sG6QlNQnmxapj/Uh/gI4mw8reQFqriPNnb5Rw9cD1POqvuB4841LjK0Qlnv2RWrZLwH31yqgelDjCsOgQAiQJBAMfqAOY0FOqLMf860JvFfvOfuzNCfDb2f5jlvZAWwrXBVrYVDi1ejiIqP2/1NO4lWVMRyxKhNVrHoQg+/V3fqeUCQQC4rpz7TOuiigoi+Am3sA0S2HyJH28qD8uZ3BaITjpWqE3abVEbLKZPdNIl/D+A3hrwYM9Td9WNO0lwaQd3UrXDAkA4/ZmyBqjr0DC5nQ+5SI0PcLrSOyLkHFN1yBDJUePCItLQZ6I6BtmoHbkl9pZXSah0SP9GWVS3g2+BxUs/hrKNAkEAgBmOBbl7EEkTcuH9S44v40yKRUqqftBp9xT0BCPOz2D6b3G3+lNkIGT1hyeKnMZyhR2BcXIDjGz9KZ2QcjHKpQJAbUrzi1RrBM9zVqj9oWhO8YlA+eNHwa9m7q7aPymhtQp7yKAhHfG2GAPL6/PiS+DmtDSHTfyhOVXH/vCmyHgp/A==";

    @PostMapping("/syncList")
    @Operation(summary = "客户管理", description = "条件查询", method = "POST")
    public Result<String> list(@RequestHeader(name = "sign") String sign,
                            @RequestBody String body) throws Exception {
        logger.info("syncList 执行了,sign：{},body：{}",sign,body);
        if(StringUtils.isBlank(sign)){
            return Result.error("验证签名为空！");
        }
        JSONObject bodyJson = JSON.parseObject(body);
        //校验签名
        String randomNum = bodyJson.getString("radomNum");
        String signCrm = getSign(secret,randomNum);
        if (!sign.equals(signCrm)){
            return Result.error("签名验证失败！");
        }
        Criteria criteria = Criteria.create();
        String date = bodyJson.getString("date");
        String createDept = bodyJson.getString("createDept");
        criteria.addCriterion("createDept", Operator.EQ, createDept);
        if(StringUtils.isBlank(date)){
            //第一次同步，拉取当天12点以前的数据
            date = DateUtil.format(new Date(),"yyyyMMdd") + " 12:00:00";
            Date runDate = DateUtil.parse(date,"yyyyMMdd HH:mm:ss");
            criteria.or()
                    .addCriterion("createTime", Operator.LE, runDate)
                    .addCriterion("updateTime", Operator.LE, runDate)
                    .end();
        }else{
            //增量同步12小时的数据
            Date startDate = DateUtil.parse(date,"yyyyMMdd HH:mm:ss");
            Date endDate = DateUtils.addHours(startDate,12);
            Junction createTimeJunction = new Junction(JunctionType.AND);
            createTimeJunction.addCriterion("createTime", Operator.GE, startDate);
            createTimeJunction.addCriterion("createTime", Operator.LE, endDate);

            Junction updateTimeJunction = new Junction(JunctionType.AND);
            updateTimeJunction.addCriterion("updateTime", Operator.GE, startDate);
            updateTimeJunction.addCriterion("updateTime", Operator.LE, endDate);
            criteria.or()
                    .addJunction(createTimeJunction)
                    .addJunction(updateTimeJunction)
                    .end();
        }

        try{
            List<CrmCustomer>  list = crmCustomerApiService.list(CrmCustomer.class,criteria);
            logger.info("返回结果---->count:{}",list.size());
            String result  = JSON.toJSONString(list);
            //公钥加密，私钥解密
            String encrypt = RSAUtils.encrypt(result,PUBLIC_KEY);
            logger.info("加密成功，result:{}",encrypt);
            logger.info("syncList 结束了");
            return Result.OK(encrypt);
        }catch (Exception e){
            logger.info("CRM系统查询主企业信息失败",e);
            return Result.error("CRM系统查询主企业信息失败");
        }
    }

    public String getSign(String secret,String radomNum){
        return SecureUtil.md5(Base64.encode(secret+radomNum));
    }



}
